package com.test.practice.socket.tcp.returns;

import lombok.Cleanup;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Description: =======================
 * @Author: Jovi
 * =======================
 * @Date: Created in 2023-02-10
 * =======================
 * @Version: 1.1.2.0
 */
public class TcpServerDemo {

    public static void main(String[] args) throws Exception {

        //1.创建服务器端的Socket，并指明自己的PORT
        @Cleanup ServerSocket ss = new ServerSocket(9999);

        //2.通过服务器端的Socket.accept() 接收来自客户端的Socket
        @Cleanup Socket socket = ss.accept();

        //3.获取客户端的Socket输入流，准备往内存输入数据
        @Cleanup InputStream is = socket.getInputStream();

        byte[] datas = new byte[10];

        @Cleanup ByteArrayOutputStream bais = new ByteArrayOutputStream();

        int len;
        //4.这里是将输入流中的数据读入到内存数组缓冲区中
        while ((len = is.read(datas)) != -1) {
            //这里的写出是将内存数组中的数据，写出到ByteArrayOutputStream中的数组中去
            bais.write(datas, 0, len);
        }

        String s = bais.toString();

        System.out.println(s);


        @Cleanup OutputStream os = socket.getOutputStream();

        os.write("我已收到消息".getBytes());

    }
}
